import { UIPlugin } from '@uppy/core'
import api from '@/api'

class SingleFileUpload extends UIPlugin {
  constructor(uppy, opt) {
    super(uppy, opt)
    this.id = this.opts.id || 'ImageCompressor'
    this.type = 'modifier'
    this.timeOut = opt.timeOut || 3000000
  }

  prepareUpload = async (fileIDs) => {
    try {
      let progress = 0
      const progressTimer = setInterval(() => {
        this.uppy.emit('progress', progress)
        progress = progress + (Math.ceil(Math.random() * 20))
        if (progress > 99) {
          progress = 99
        }
      }, 1000)
      const file = this.uppy.getFile(fileIDs[0])
      const uploadData = await api.file.getUploadData({file: file})
      if (uploadData?.data) {
        await api.file.uploadFile({file: file})
        clearInterval(progressTimer)
        this.uppy.emit('progress', 100)
        return uploadData.data
      }
      throw (new Error('prepareUpload error'))
    } catch (err) {
      this.uppy.removeFile(fileIDs[0], 'preload error')
      throw (new Error('prepareUpload error'))
    }
    
  }

  install () {
    this.uppy.addPreProcessor(this.prepareUpload)
  }

  uninstall () {
    this.uppy.removePreProcessor(this.prepareUpload)
  }
}

export default SingleFileUpload